package com.disease.api.service.web.death;

import com.alibaba.fastjson.JSONObject;
import com.disease.api.service.entity.*;
import com.disease.api.service.entity.eumns.RoleEnum;
import com.disease.api.service.mapper.DeathCardWorkFlowMapper;
import com.disease.api.service.mapper.DeathReportInfoMapper;
import com.disease.api.service.mapper.EmrDeathReportInfoReviewMapper;
import com.disease.api.service.model.request.EmrDeathInfoRequest;
import com.disease.api.service.model.ResponseResult;
import com.disease.api.service.model.request.OperateRequest;
import com.disease.api.service.model.request.PatientRequest;
import com.disease.api.service.model.response.EmrDeathInfoResponse;
import com.disease.api.service.model.response.EmrDeathListResponse;
import com.disease.api.service.service.CommonService;
import com.disease.api.service.service.DeathInfoService;
import com.disease.api.service.service.ICDService;
import com.disease.api.service.web.BaseController;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@RestController
@RequestMapping(value = "/disease/v1/api/death")
public class DeathController extends BaseController {



    @Autowired
    private DeathInfoService deathInfoService;

    @Autowired
    EmrDeathReportInfoReviewMapper emrDeathReportInfoReviewMapper;

    @Autowired
    ICDService icdService;

    @Autowired
    private CommonService commonService;

    @Autowired
    private DeathReportInfoMapper deathReportInfoMapper;

    @Autowired
    private DeathCardWorkFlowMapper deathCardWorkFlowMapper;



    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public ResponseResult<PageInfo<EmrDeathListResponse>> list(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestBody EmrDeathInfoRequest emrDeathInfoRequest) {
        PageInfo<EmrDeathListResponse> emrDeathInfoPageInfo = deathInfoService.queryEmrDeathInfoByPage(getBaseUser(),pageNum, pageSize, emrDeathInfoRequest);
        return ResponseResult.success(emrDeathInfoPageInfo);
    }

    @ResponseBody
    @PostMapping(value = "/info")
    public ResponseResult<EmrDeathInfoResponse> info(@RequestBody PatientRequest patientRequest) {
        return ResponseResult.success(deathInfoService.queryEmrDeathInfoById(getBaseUser(),patientRequest));
    }

    /**
     * 手动上报死亡卡功能
     * @param patientId
     * @return
     */
    @ResponseBody
    @GetMapping(value = "/manualReport")
    public ResponseResult<EmrDeathInfoResponse> manualReport(
            @RequestParam("patientId") String patientId) {
        boolean number = commonService.isNumber(patientId);
        if(!number){
            return ResponseResult.fail("请输入非中文类型患者ID");
        }
        return ResponseResult.success(deathInfoService.queryEmrDeathInfoByPatientId(getBaseUser(),patientId));
    }

    @ResponseBody
    @PostMapping(value = "/operate")
    public ResponseResult operate(
            @RequestBody OperateRequest operateRequest) {
        return deathInfoService.operateDeathCardFLow(getBaseUser(), operateRequest);
    }

    @ResponseBody
    @PostMapping(value = "/todoList")
    public ResponseResult<List<DeathReportInfo>> todoList(@RequestBody EmrDeathInfoRequest emrDeathInfoRequest) {
        return ResponseResult.success(deathInfoService.todoList(getBaseUser(), emrDeathInfoRequest));
    }

    @ResponseBody
    @GetMapping(value = "/todolistCount")
    public ResponseResult<Integer> todoList() {
        return ResponseResult.success(deathInfoService.todoListCount(getBaseUser()));
    }


    @ResponseBody
    @PostMapping(value = "/edit")
    public ResponseResult<String> edit(@RequestBody EmrDeathInfoResponse emrDeathInfoResponse) {
        try {
            if(Optional.ofNullable(emrDeathInfoResponse.getPkId()).isPresent()&&emrDeathInfoResponse.getPkId()>0){
                long pkId = emrDeathInfoResponse.getPkId();
                DeathReportInfoReview deathReportInfoReviewRequest = new DeathReportInfoReview();
                deathReportInfoReviewRequest.setPkId(pkId);
                deathReportInfoReviewRequest.setContent(JSONObject.toJSONString(emrDeathInfoResponse));
                deathReportInfoReviewRequest.setIdCard(emrDeathInfoResponse.getIdcardCode());
                DeathReportInfoReview deathReportInfoReviewHistory = emrDeathReportInfoReviewMapper.selectByQuery(DeathReportInfoReview.builder().pkId(pkId).build());
                if(deathReportInfoReviewHistory!=null&&!deathReportInfoReviewHistory.getIdCard().equals(emrDeathInfoResponse.getIdcardCode())){
                    //更新emr_death_Info的id_card
                    deathReportInfoMapper.updateByIdCard(deathReportInfoReviewHistory.getIdCard(),emrDeathInfoResponse.getIdcardCode());
                    deathCardWorkFlowMapper.updateWorkFlowBySeries(deathReportInfoReviewHistory.getIdCard(),emrDeathInfoResponse.getIdcardCode());
                }
                emrDeathReportInfoReviewMapper.update(deathReportInfoReviewRequest);
            }else{
                DeathReportInfoReview deathReportInfoReview = new DeathReportInfoReview();
                if(Optional.ofNullable(emrDeathInfoResponse.getId()).isPresent()&& !StringUtils.isBlank(emrDeathInfoResponse.getId())){
                    deathReportInfoReview.setDeathId(emrDeathInfoResponse.getId());
                }
                if(Optional.ofNullable(emrDeathInfoResponse.getPatientId()).isPresent()&& !StringUtils.isBlank(emrDeathInfoResponse.getPatientId())){
                    deathReportInfoReview.setPatientId(emrDeathInfoResponse.getPatientId());
                }
                deathReportInfoReview.setContent(JSONObject.toJSONString(emrDeathInfoResponse));
                deathReportInfoReview.setIdCard(Optional.ofNullable(emrDeathInfoResponse.getIdcardCode()).orElse("-"));
                deathReportInfoReview.setPatientName(Optional.ofNullable(emrDeathInfoResponse.getName()).orElse("-"));

                DeathReportInfoReview deathReportInfoReviewResponse = emrDeathReportInfoReviewMapper.selectByQuery(DeathReportInfoReview.builder().idCard(emrDeathInfoResponse.getIdcardCode()).build());
                if(deathReportInfoReviewResponse!=null){
                    return ResponseResult.fail("患者身份证号码已报送，请核实");
                }
                emrDeathReportInfoReviewMapper.insertOne(deathReportInfoReview);
            }
            return ResponseResult.success("更新死亡报送数据成功");
        }catch (Exception e){
            log.error("更新死亡报送数据失败:{}",e.getMessage());
            return ResponseResult.fail("更新死亡报送数据失败");
        }
    }

    /**
     * 死亡卡管理列表
     * @param pageNum
     * @param pageSize
     * @param deathReportInfo
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/deathCardList")
    public ResponseResult<PageInfo<DeathReportInfo>> deathCardList(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestBody DeathReportInfo deathReportInfo) {
        BaseUser baseUser = getBaseUser();
        //医生仅能访问本部门数据
        if(baseUser.getRole().equals(RoleEnum.DOCTOR.getRoleId())){
            deathReportInfo.setDeptCode(baseUser.getDeptCode());
        }
        return ResponseResult.success(deathInfoService.queryDeathCardList(pageNum,pageSize,baseUser,deathReportInfo));
    }

    /**
     * 死亡卡查重
     * @param idCard
     * @return
     */
    @ResponseBody
    @GetMapping(value = "/findDeathCard")
    public ResponseResult findDeathCard(@RequestParam String idCard) {
        return deathInfoService.findRepeatCardNoByIdCard(idCard);
    }


    @ResponseBody
    @RequestMapping(value = "/query/icd", method = RequestMethod.GET)
    public ResponseResult<List<ICD>> queryRegion(@RequestParam("name") String name){
        return ResponseResult.success(icdService.queryICDCodeByName(name));
    }


}
